const { axios, getToken } = require("./weix");
var {
  weix: { QRcode },
} = require("../config");
/**
 * 获取微信二维码图片连接
 * @param {Number | String} sceneInfo 场景值
 * @param {Number} seconds 二维码有效时间， 默认为配置时间
 * @param {Boolean} permanent 是否为永久二维码, 默认false
 * @returns {Promise(sting)}  返回带二维码图片的链接
 */
exports.getQRcode = async function (sceneInfo, seconds, permanent) {
  try {
    const actionName = "";
    const actionExp = !!permanent ? "_LIMIT" : "";
    const scene = {};
    if (typeof sceneInfo === "number") {
      actionName = "QR" + actionExp + "_SCENE";
      scene = { scene_id: sceneInfo };
    } else if (typeof sceneInfo === "string") {
      actionName = "QR" + actionExp + "_STR_SCENE";
      scene = { scene_str: sceneInfo };
    } else {
      actionName = "QR" + actionExp + "_SCENE";
      scene = { scene_id: 0 };
    }
    seconds = seconds || QRcode.expireSeconds;

    return axios
      .post("cgi-bin/qrcode/create?access_token=" + (await getToken()), {
        expire_seconds: seconds, //二维码有效时间 单位s 默认30s
        action_name: actionName, //二维码类型，QR_SCENE为临时的整型参数值，QR_STR_SCENE为临时的字符串参数值,QR_LIMIT_SCENE为永久的整型参数值，QR_LIMIT_STR_SCENE为永久的字符串参数值
        action_info: {
          scene: scene,
        },
      })
      .then((res) => {
        if (!res.data.errcode) {
          return QRcode.baseURL + res.data.ticket;
        } else {
          throw Error(`getQRcode(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("getQRcode()", e.message);
  }
};

/**
 * 微信长连接转短链接
 * @param {String} url 需要转换的长链接，支持http://、https://、weixin://wxpay 格式的url
 * @returns {Promise(String)} 返回转换后的短链接
 */
exports.long2short = async function (url) {
  try {
    return axios
      .post("cgi-bin/shorturl?access_token=" + (await getToken()), {
        action: "long2short",
        long_url: url,
      })
      .then((res) => {
        if (!res.data.errcode) {
          return res.data.short_url;
        } else {
          throw Error(`long2short(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("long2short()", e.message);
  }
};

exports.shorten = async function (long_data, expire) {
  try {
    return axios
      .post("cgi-bin/shorturl?access_token=" + (await getToken()), {
        long_data,
        expire_seconds: expire,
      })
      .then((res) => {
        if (res.data.errcode === 0) {
          return res.data.short_key;
        } else {
          throw Error(`long2short(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("long2short()", e.message);
  }
};

/**
 * 创建一个标签
 * @param {String} name 标签名称
 * @returns {Promise(Number)}
 */
exports.createtag = async function (name) {
  try {
    return axios
      .post("cgi-bin/tags/create?access_token=" + (await getToken()), {
        tag: { name },
      })
      .then((res) => {
        console.log(res.data);
        if (!res.data.errcode) {
          return res.data.id;
        } else {
          throw Error(`creattag(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("creattag():", e.message);
  }
};

/**
 * 返回创建的编号
 * @returns {Promise(Object)}
 * @param {[Object]} obj.tags 所有的标签组合
 * @param {Number} tag.id     标签id
 * @param {String} tag.name   标签名称
 * @param {Number}  tag.count  此标签下的粉丝数
 */
exports.gettags = async function () {
  try {
    return axios
      .get("cgi-bin/tags/get?access_token=" + (await getToken()))
      .then((res) => {
        if (!res.data.errcode) {
          return res.data;
        } else {
          throw Error(`gettags(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("gettags():", e.message);
  }
};

/**
 * 修改一个标签
 * @param {Number} id   标签编号
 * @param {String} name 标签名称
 * @returns {Promise(Boolean)}
 */
exports.updatetag = async function (id, name) {
  try {
    return axios
      .post("cgi-bin/tags/update?access_token=" + (await getToken()), {
        tag: { id, name },
      })
      .then((res) => {
        if (!res.data.errcode) {
          return true;
        } else {
          throw Error(`updatetag(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("updatetag():", e.message);
  }
};

/**
 * 删除一个标签
 * @param {Number} id   标签编号
 * @returns {Promise(Boolean)}
 */
exports.deletetag = async function (id) {
  try {
    return axios
      .post("cgi-bin/tags/delete?access_token=" + (await getToken()), {
        tag: { id },
      })
      .then((res) => {
        if (!res.data.errcode) {
          return true;
        } else {
          throw Error(`deletetag(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("deletetag():", e.message);
  }
};

/**
 * 获取一个标签下粉丝列表
 * @param {Number} id   标签编号
 * @returns {Promise(Object)}
 * @param {Number} obj.count  粉丝数
 * @param {Object} obj.data
 * @param {String} obj.next_openid  拉取列表最后一个用户的openid
 * @param {Array}  data.openid 用户微信号数组
 */
exports.gettagusers = async function (id) {
  try {
    return axios
      .post("cgi-bin/user/tag/get?access_token=" + (await getToken()), {
        tag: { id },
      })
      .then((res) => {
        if (!res.data.errcode) {
          return res.data;
        } else {
          throw Error(`gettaguser(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("gettaguser():", e.message);
  }
};

/**
 * 批量为用户打标签
 * @param {[String]} openid 批量用户id
 * @param {Number} tagid   标签编号
 * @returns {Promise(Boolean)}
 */
exports.batchtagging = async function (openid, tagid) {
  try {
    return axios
      .post(
        "cgi-bin/tags/members/batchtagging?access_token=" + (await getToken()),
        {
          openid_list: openid,
          tagid,
        }
      )
      .then((res) => {
        if (!res.data.errcode) {
          return true;
        } else {
          throw Error(`batchtagging(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("batchtagging():", e.message);
  }
};

/**
 * 批量为用户取消标签
 * @param {[String]} openid 批量用户id
 * @param {Number} tagid   标签编号
 * @returns {Promise(Boolean)}
 */
exports.batchuntagging = async function (openid, tagid) {
  try {
    return axios
      .post(
        "cgi-bin/tags/members/batchuntagging?access_token=" +
          (await getToken()),
        {
          tag: { openid_list: openid, tagid },
        }
      )
      .then((res) => {
        if (!res.data.errcode) {
          return true;
        } else {
          throw Error(`batchuntagging(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("batchuntagging():", e.message);
  }
};

/**
 * 批量为用户取消标签
 * @param {String} openid 批量用户id
 * @param {Number} tagid   标签编号
 * @returns {Promise(Boolean)}
 */
exports.getidlist = async function (openid) {
  try {
    return axios
      .post("cgi-bin/tags/getidlist?access_token=" + (await getToken()), {
        tag: { openid },
      })
      .then((res) => {
        if (!res.data.errcode) {
          return res.data;
        } else {
          throw Error(`getidlist(): ${res.data.errmsg}`);
        }
      });
  } catch (e) {
    console.log("getidlist():", e.message);
  }
};

/**
 * 获取所有关注的用户openid
 * @param {?String} next 本次第一个的openid
 * @returns {Object} 关注用户列表
 * @param {Number} obj.total  关注的总人数
 * @param {Number} obj.count  拉取的openid 个数，最大1000
 * @param {Object} obj.data   Openid 列表
 * @param {String} obj.next_openid  拉取列表的最后一个用户的OPENID
 * @param {[String]} obj.data.openid  openid 数组
 */
exports.getAllUserOpenid = async function (next) {
  try {
    const url =
      "cgi-bin/user/get?access_token=" +
      (await getToken()) +
      (!!next ? "&next_openid=" + next : "");
    return axios.get(url).then((res) => {
      if (!res.data.errcode) {
        return res.data;
      } else {
        throw Error(`getAllUserOpenid(): ${res.data.errmsg}`);
      }
    });
  } catch (e) {
    console.log("getAllUserOpenid():", e.message);
  }
};
